L01-TwoSum
又是一个轮回的开始,请记录一下,什么时间结束.
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
public int[] twoSum(int[] nums, int target) {
if(nums== null || nums.length==0 ) {
return new int[2];
}
HashMap<Integer,Integer> cache = new HashMap<>(nums.length);
for (int i = 0; i < nums.length; i++) {
if(cache.get(target-nums[i]) != null){
return new int[]{cache.get(target-nums[i]),i};
}
cache.put(nums[i],i);
}
return new int[2];
}